package com.southern.gateway.filter;

import java.net.URI;
import java.util.Arrays;
import java.util.List;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import reactor.core.publisher.Mono;


public class LocationFilter extends AbstractGatewayFilterFactory<LocationFilter.Config> {

	public LocationFilter()
	{
		super(Config.class);
	}
	
	public static class Config {
		public String getTarget() {
			return target;
		}

		public void setTarget(String target) {
			this.target = target;
		}

		public String getReplacement() {
			return replacement;
		}

		public void setReplacement(String replacement) {
			this.replacement = replacement;
		}

		private String target;
		private String replacement;
    }

	@Override
	public List<String> shortcutFieldOrder() {
		return Arrays.asList("target",
				"replacement");
	}

	@Override
	public GatewayFilter apply(Config config) {
		return (exchange, chain)->{
			return chain.filter(exchange).then(
				Mono.fromRunnable(() -> {
				List<String> loctions = exchange.getResponse().getHeaders().get("location");
				if(!CollectionUtils.isEmpty(loctions))
				{
					String loction = loctions.get(0);
					if(StringUtils.startsWithIgnoreCase(loction, config.getTarget()))
					{
						String newLoction = loction.replace(config.getTarget() , config.getReplacement());
						exchange.getResponse().getHeaders().setLocation(URI.create(newLoction));
					}
				}
				
			})); //end then
		};
	}
}
